#!/bin/bash
set -e

# nfs 共享目录
NfS_SHARED_DIRECTORY="/zpaas/data/v1"
NfS_SHARED_IP="10.10.192.0/24"
MASTER_IP="10.10.192.220"

function main() {
    ch0_init
    ch1_nfs_install
    ch2_elasticsearch_install
    ch3_kibana_install
    ch4_fluentd_install
}

function load_images() {
  # docker镜像在百度云
  sudo docker load < elasticsearch_7_2_0.tar.gz
  sudo docker load < fluentd.tar.gz
  sudo docker load < kibana_7_2_0.tar.gz
  sudo docker load < nfs-client-provisioner.tar.gz
  sudo docker load < nginx.tar.gz
  sudo docker load < busybox.tar.gz
}

function ch0_init() {
  cd ch0_init
  #load_images

  sudo kubectl create -f  kube-logging-namespace.yaml
  sudo kubectl create -f  busybox-pod.yaml
  # 查看部署状态
  sudo kubectl get pod|grep counter
  cd ..
}

function ch1_nfs_install() {
  cd ch1_nfs

  install_nfs_service
  sed -i s@/data/v1@$NfS_SHARED_DIRECTORY@g nfs-deployment.yaml
  sed -i s/192.168.40.180/$MASTER_IP/g nfs-deployment.yaml
  sudo kubectl create -f nfs_serviceaccount.yaml
  sudo kubectl create -f nfs-rbac.yaml
  sudo kubectl apply -f nfs-deployment.yaml
  sudo kubectl apply -f nfs-class.yaml

  # 查看部署状态
  sleep 3
  sudo kubectl get pod,svc|grep nfs
  cd ..
}

function ch2_elasticsearch_install() {
cd ch2_elasticsearch
# 创建 headless service 服务
sudo kubectl apply -f elasticsearch_svc.yaml
# 创建 NodePort service 服务方便 GoLang 操作elastic api做测试(仅供参考)
#sudo kubectl apply -f elasticsearch_svc_nodeport.yaml

# 如果主机性能资源不够可以部署单节点
sudo kubectl apply -f elasticsearch-statefulset-single.yaml
# 创建es 集群
#sudo kubectl apply -f elasticsearch-statefulset-ha.yaml

# wait es pod running
sleep 3
sudo kubectl port-forward es-cluster-0 9200:9200 --namespace=kube-logging

# 查看部署状态
sudo kubectl get svc,pod --namespace=kube-logging|grep -e es-cluster -e elasticsearch
cd ..
}

function ch3_kibana_install() {
cd ch3_kibana
sudo kubectl apply -f kibana.yaml
# 查看部署状态
sleep 3
sudo kubectl get pods,svc -n kube-logging|grep kibana
cd ..
}

function ch4_fluentd_install() {
cd ch4_fluentd
sudo kubectl apply -f fluentd.yaml
# 查看部署状态
sleep 3
sudo kubectl get pods -n kube-logging|grep fluentd
cd ..
}

# 建议手动安装部署
function insatll_nfs_service() {
# 安装
sudo yum install nfs-utils -y
# 启动
sudo systemctl start nfs
sudo systemctl status nfs
sudo systemctl enable nfs.service
# 上创建一个 nfs 共享目录
sudo mkdir $NfS_SHARED_DIRECTORY -p
sudo chmod 777 $NfS_SHARED_DIRECTORY

sudo chmod a+w /etc/exports
# ip 需要修改
sudo cat >> /etc/exports << EOF
$NfS_SHARED_DIRECTORY $NfS_SHARED_IP(rw,no_root_squash)
EOF
cat /etc/exports
#加载配置，使配置生效
sudo exportfs -arv
sudo systemctl restart nfs

# 禁用了 selfLink
# 生效
#sudo kubectl apply -f /etc/kubernetes/manifests/kube-apiserver.yaml
}

main